﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Web;
using System.IO;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using Core.Library;

namespace WebApplication1.uploadify
{    
    public class Upload : IHttpHandler
    {
        protected string SecretKey = WebConfigurationManager.AppSettings["SecretKey"];
        protected string LargeFile = WebConfigurationManager.AppSettings["LargeFile"];
        protected string SmallFile = WebConfigurationManager.AppSettings["SmallFile"];

        public Upload()
        {
            FillMimes();
        }

        protected Dictionary<string, string> Mimes;

        private void FillMimes()
        {
            if (Mimes == null) Mimes = new Dictionary<string, string>();
            Mimes.Add(".jpeg", "image/jpeg");
            Mimes.Add(".jpg", "image/jpeg");
            Mimes.Add(".gif", "image/gif");
            Mimes.Add(".png", "image/png");
        }

        private string GetMime(string fileName)
        {
            if (fileName.Contains("."))
            {
                var ext = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));
                return Mimes.ContainsKey(ext) ? Mimes[ext] : string.Empty;
            }
            return string.Empty;
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpPostedFile file = context.Request.Files["filedata"];

                var userId      = ConvertUtility.ConvertTo<int>(context.Request.QueryString["UserId"]);                

                if (userId > 0)
                {
                    //var folderPath = string.Format("/Data/UserData/{0}/", userId);
                    //var folder = context.Server.MapPath(folderPath);

                    //if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

                    //var strPath = folderPath + file.FileName;
                    //var strFile = context.Server.MapPath(strPath);

                    //file.SaveAs(strFile);

                    //var fileSize = file.ContentLength / 1000;
                    //context.Response.Write(string.Format("{0},{1},{2}", strFile, file.FileName, fileSize));
                    //context.Response.StatusCode = 200;    

                    //-----------------------

                    var dt = DateTime.Now;


                    var encryptFileName = string.Format("{0}{1}{2}{3}{4}", dt.Year, dt.Month, dt.Day, dt.Minute, dt.Second);
                    var rawFileName = Path.GetFileNameWithoutExtension(file.FileName.ToLower());
                    rawFileName = "-" + UnicodeUtility.UnicodeToKoDauAndGach(rawFileName);
                    var fileExtension   = Path.GetExtension(file.FileName.ToLower());

                    var fileName = string.Format("files/{0}/{1}/{2}/{3}/{4}", userId, dt.Year, dt.Month, dt.Day, encryptFileName + rawFileName + fileExtension);                    

                    var urlAction = SmallFile + "upload";

                    var parameters = new NameValueCollection { { "filename", fileName }, { "secret_key", SecretKey } };                    
                    var resp = (HttpWebResponse)HttpMethodHelper.PostFile(new Uri(urlAction), parameters, file.InputStream, fileName, GetMime(fileName), "filedata", null, null);

                    var result = false;
                    if (resp.StatusCode == HttpStatusCode.OK) result = true;
                    resp.Close();                    

                    var objSerial = new JavaScriptSerializer();
                    var json = objSerial.Serialize(result);
                    context.Response.Write(json);            
                }                
            }
            catch (Exception ex)
            {
                context.Response.Write("Uploadify Error: " + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}